import axios from 'axios'
import {message, Modal} from 'ant-design-vue';
import {clearLocalData} from '@/utils/authUtils.js';
import * as loadingUtils from '@/utils/loadingUtils.js';

const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 10000,
})

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'


const error = () => {
    Modal.error({
        title: '提示：',
        okText: '重新登录',
        content: '登录已失效， 请重新登录',
        onOk: () => {
            clearLocalData()
            window.location.reload()
        }
    })
}

service.interceptors.request.use(config => {
    loadingUtils.startLoading()
    if (config.url.startsWith('/portal')) {
        config.headers['satoken'] = localStorage.getItem('PORTAL_TOKEN')
    } else {
        config.headers['satoken'] = localStorage.getItem('TOKEN')
    }
    return config
})

service.interceptors.response.use(
    res => {
        loadingUtils.stopLoading()
        const data = res.data
        const code = data.code

        if (code === 401) {
            error()
        }

        if (code === 500) {
            message.error(data.msg).then(r => {})
            return Promise.reject(data)
        }

        return res.data.data
    },
    err => {
        return Promise.reject(err)
    }
)

export default service
